<template>
  <div class="business">
    <el-form :inline="true" :model="queryInfo" class="demo-form-inline">
      <el-form-item label="客户姓名">
        <el-input v-model="queryInfo.name" placeholder="请输入客户姓名" clearable />
      </el-form-item>
      <el-form-item label="客户手机">
        <el-input v-model="queryInfo.phone" placeholder="请输入客户手机号码" clearable />
      </el-form-item>
      <el-form-item label="归属人">
        <el-input v-model="queryInfo.owner" placeholder="请输入商机归属人" clearable />
      </el-form-item>

      <el-form-item label="跟进时间">
        <el-date-picker
          v-model="timeArray"
          type="datetimerange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD HH:mm:ss"
          date-format="YYYY/MM/DD ddd"
          time-format="A hh:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="onSubmit">搜索</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row>
      <el-button dark type="primary" plain @click="handleAdd">
        <el-icon>
          <Plus />
        </el-icon>
        新增
      </el-button>
      <el-button dark type="success" plain @click="handleEdit">
        <el-icon>
          <Edit />
        </el-icon>
        修改
      </el-button>
      <el-button dark type="danger" plain @click="handleDelete">
        <el-icon>
          <Delete />
        </el-icon>
        删除
      </el-button>
      <el-button dark type="warning" plain @click="exportToExcel">
        <el-icon>
          <Download />
        </el-icon>
        导出
      </el-button>
    </el-row>
    <el-table
      :data="opportunitiesData" style="width: 100%; margin-top: 20px"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column prop="name" label="客户姓名" align="center" fixed />
      <el-table-column prop="phone" label="手机号码" align="center" width="150" />
      <el-table-column prop="owner" label="商机归属" align="center" />
      <el-table-column prop="createTime" label="创建时间" align="center" width="180" />
      <el-table-column prop="" label="商机状态" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.status===1" size="small">已分配</el-tag>
          <el-tag v-else-if="scope.row.status===2" type="success" size="small">进行中</el-tag>
          <el-tag v-else type="info" size="small">未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="nextTime" label="下次跟进时间" align="center" width="180" />
      <el-table-column prop="" label="商机状态" align="center" width="230" fixed="right">
        <template #default="scope">
          <el-button text type="primary" size="small" @click="handleDetails(scope.row,isFalse)">
            <el-icon>
              <View />
            </el-icon>
            查看
          </el-button>
          <el-button v-if="scope.row.status===1" text type="primary" size="small"
                     @click="handleAllocation(scope.row,)">
            <el-icon>
              <Pointer />
            </el-icon>
            分配
          </el-button>
          <el-button v-if="scope.row.status===2||scope.row.status===1" text type="primary" size="small"
                     @click="handleDetails(scope.row,isTrue)">
            <el-icon>
              <TopRight />
            </el-icon>
            跟进
          </el-button>
        </template>

      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      v-model:page="queryInfo.pageNum"
      v-model:limit="queryInfo.pageSize"
      :total="total"
      @pagination="getOpportunitiesListData">
    </pagination>
  </div>
  <el-dialog v-model="editDialogFormVisible" :title="ids2.length>0?'修改商机':'新增商机'" width="700">
    <el-form :model="opportunityDetailsForm" label-width="80" :rules="rules">
      <el-row>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="opportunityDetailsForm.phone" autocomplete="off" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户姓名" prop="name">
            <el-input v-model="opportunityDetailsForm.name" autocomplete="off" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="渠道来源">
            <el-select v-model="opportunityDetailsForm.channelId" placeholder="请选择渠道来源">
              <el-option
                v-for="item in channelsData" :key="item.channelId" :label="item.channelName"
                :value="item.channelId" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="活动信息">
            <el-select v-model="opportunityDetailsForm.activityId" placeholder="请选择渠道来源">
              <el-option
                v-for="item in activitiesData" :key="item.activityId" :label="item.info"
                :value="item.activityId" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户性别">
            <el-radio-group v-model="opportunityDetailsForm.gender">
              <el-radio :value="1" :label="1">男</el-radio>
              <el-radio :value="2" :label="2">女</el-radio>
              <el-radio :value="0" :label="0">未知</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户年龄">
            <el-input-number
              v-model="opportunityDetailsForm.age" :min="1" :max="999" placeholder="年龄"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="微信号">
            <el-input v-model="opportunityDetailsForm.weixin" autocomplete="off" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="QQ号码">
            <el-input v-model="opportunityDetailsForm.qq" autocomplete="off" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button v-if="ids2.length>0" type="primary" @click="handleSubmitEdit">确定</el-button>
        <el-button v-else type="primary" @click="handleSubmitAdd">确定</el-button>
        <el-button @click="editDialogFormVisible = false">
          取消
        </el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-model="allocationDialogFormVisible" title="分配商机" width="500">
    <el-form :model="departmentsForm" label-width="80">
      <el-row>
        <el-col :span="12">
          <el-form-item label="归属部门">
            <el-tree-select
              v-model="departmentsForm.departmentId"
              :data="departmentsList"
              :props="{ children: 'children', label: 'label', value: 'id' }"
              check-strictly
              :render-after-expand="false"
              style="width: 240px"
              @node-click="handleNodeClick"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分配给">
            <el-select v-model="departmentsForm.deptId" placeholder="请选择分配">
              <el-option
                v-for="item in  departmentsInformationList" :key="item.deptId" :label="item.nickName"
                :value="item.deptId" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmitAllocation">确定
        </el-button>
        <el-button @click="allocationDialogFormVisible = false">
          取消
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import {
  getOpportunitiesList,
  deleteOpportunities,
  getChannels,
  getOpportunityById,
  updateOpportunity,
  getDepartmentsList,
  getActivityById,
  addOpportunity, getDepartmentById, assignOpportunities
} from '@/api/business/business';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import Pagination from '@/components/Pagination/index.vue';
import { useRouter, useRoute } from 'vue-router';
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';

const tableData = ref([
  { name: 'John Doe', email: 'john@example.com' },
  { name: 'Jane Doe', email: 'jane@example.com' }
]);

// 导出到Excel
function exportToExcel() {
  const ws = XLSX.utils.json_to_sheet(opportunitiesData.value);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

  const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });

  function s2ab(s) {
    const buf = new ArrayBuffer(s.length);
    const view = new Uint8Array(buf);
    for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
    return buf;
  }

  saveAs(
    new Blob([s2ab(wbout)], { type: 'application/octet-stream' }),
    'data.xlsx'
  );
}

const router = useRouter();
const route = useRoute();

// 定义查询参数
const queryInfo = ref({
  createBy: '',
  createTime: '',
  name: '',
  owner: '',
  params: {},
  phone: '',
  remark: '',
  searchValue: '',
  updateBy: '',
  updateTime: '',
  pageNum: 1,
  pageSize: 10
});
const timeArray = ref([]);
const total = ref(0);
// 定义商机列表数据
const opportunitiesData = ref([]);
// 获取商机列表数据
const getOpportunitiesListData = () => {
  getOpportunitiesList(queryInfo.value).then((res: any) => {
    if (res.code !== 200) return ElMessage.error(res.msg);
    console.log(res);
    opportunitiesData.value = res.rows;
    total.value = res.total;
  });
};
// 精确查询
const onSubmit = () => {
  getOpportunitiesListData();
};
// 重置查询参数
const onReset = () => {
  queryInfo.value = {
    createBy: '',
    createTime: '',
    name: '',
    owner: '',
    params: {},
    phone: '',
    remark: '',
    searchValue: '',
    updateBy: '',
    updateTime: '',
    pageNum: 1,
    pageSize: 10
  };
  timeArray.value = [];
  getOpportunitiesListData();
};

// 定义选中的数据
const ids = ref([]);
let ids2 = ref([]);
const handleSelectionChange = (event: any) => {
  ids.value = event.map((item: any) => item.businessId);
  // console.log(ids.value);
};


// 删除商机
const handleDelete = () => {
  if (ids.value.length <= 0) {
    ElMessage.error('请选择要删除的商机');
  } else {
    ElMessageBox.confirm(
      `确定要删除选中的${ids.value.length}条数据吗?`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
      .then(() => {
        deleteBusiness(ids.value);
        ElMessage({
          type: 'success',
          message: '删除成功'
        });
        getOpportunitiesListData();
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除'
        });
      });
  }
};
// 删除的方法
const deleteBusiness = (businessIds: any) => {
  deleteOpportunities(businessIds).then((res: any) => {
    // console.log(res);
  });
};

// 修改商机数据
const editDialogFormVisible = ref(false);
const opportunityDetailsForm = ref({
  activityId: null,
  age: 0,
  businessId: 0,
  channelId: null,
  createTime: '',
  gender: 0,
  name: '',
  nextTime: '',
  owner: '',
  phone: '',
  qq: '',
  status: 0,
  weixin: ''
});
const handleEdit = () => {
  ids2.value = ids.value;
  if (ids2.value.length !== 1) {
    ElMessage.error('请选择一条数据进行修改');
  } else {
    editDialogFormVisible.value = true;
    // 根据id查询商机详情
    getOpportunityById(ids2.value[0]).then((res: any) => {
      // console.log(res);
      opportunityDetailsForm.value = res.data;
    });
    // 获取渠道来源
    getChannelsData();
  }
};
const handleAdd = () => {
  editDialogFormVisible.value = true;
  opportunityDetailsForm.value = {
    activityId: null,
    age: 0,
    businessId: 0,
    channelId: null,
    createTime: '',
    gender: 0,
    name: '',
    nextTime: '',
    owner: '',
    phone: '',
    qq: '',
    status: 0,
    weixin: ''
  };
  ids2.value = [];
  // 获取渠道来源
  getChannelsData();
};
// 渠道列表
const channelsData = ref([]);
// 活动列表
const activitiesData = ref([]);
// 获取渠道来源
const getChannelsData = () => {
  getChannels().then((res: any) => {
    // console.log(res);
    channelsData.value = res.data;
  });
};
watch(() => opportunityDetailsForm.value.channelId, (newVal: any) => {
  activitiesData.value = [];
  getActivity(newVal);
});
// 查询活动信息
const getActivity = (channelId: number) => {
  getActivityById(channelId).then((res: any) => {
    // console.log(res);
    activitiesData.value = res.data;
  });
};
// 确定修改
const handleSubmitEdit = () => {
  updateOpportunity(opportunityDetailsForm.value).then((res: any) => {
    // console.log(res);
    if (res.code !== 200) return ElMessage.error(res.msg);
    editDialogFormVisible.value = false;
    ElMessage.success('修改成功');
    getOpportunitiesListData();
  });
};
// 确认添加
const handleSubmitAdd = () => {
  addOpportunity(opportunityDetailsForm.value).then((res: any) => {
    if (res.code !== 200) return ElMessage.error(res.msg);
    editDialogFormVisible.value = false;
    ElMessage.success('添加成功');
    getOpportunitiesListData();
  });
};
// 表单验证规则
const rules = {
  phone: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }]
};

// 分配商机
const allocationDialogFormVisible = ref(false);
// 部门列表
const departmentsList = ref([]);
// 分配商机表单数据
const departmentsForm = ref({
  assignId: 0,
  departmentId: null,
  deptId: null,
  nickName: '',
  type: 1,
  userId: 1,
  userName: 'admin'
});
// 打开分配弹框
const handleAllocation = (row: any) => {
  allocationDialogFormVisible.value = true;
  console.log(row.businessId);
  departmentsForm.value.assignId = row.businessId;
  getDepartmentsListData();
};
// 查询部门列表
const getDepartmentsListData = async () => {
  const res: any = await getDepartmentsList();
  if (res.code !== 200) {
    ElMessage.error(res.msg);
    return;
  }
  departmentsList.value = res.data;

  // 数据加载完成后检查并设置选中的值
  if (!departmentsForm.value.departmentId) {
    departmentsForm.value.departmentId = departmentsList.value[0]?.id || null;
  }
};

// 点击获取部门具体信息
const handleNodeClick = (event: any) => {
  console.log(event.id);
  getDepartmentByIdData(event.id);

};
const departmentsInformationList = ref([]);
// 根据id查询部门具体信息
const getDepartmentByIdData = (id: number) => {
  getDepartmentById(id).then((res: any) => {
    if (res.code !== 200) return ElMessage.error(res.msg);
    console.log(res);
    departmentsInformationList.value = res.data;
  });
};
// 确认分配商机
const handleSubmitAllocation = () => {
  assignOpportunities(departmentsForm.value).then((res: any) => {
    console.log(res);
    if (res.code !== 200) return ElMessage.error(res.msg);
    allocationDialogFormVisible.value = false;
    ElMessage.success('分配成功');
    getOpportunitiesListData();
  });
};

// 查看详情
const isFalse = ref('false');
const isTrue = ref('true');
const handleDetails = (row: any, isFollow: string) => {
  router.push({
    path: '/business/view', query: {
      id: row.businessId,
      isFollow
    }
  });
};
// watch(
//     () => timeArray.value,
//     (newValue, oldValue) => {
//         if (newValue) {
//             const startTime = newValue[0];
//             const endTime = newValue[1];
//             // 将起始时间和结束时间转换为 ISO 8601 格式字符串
//             const isoStartTime = startTime.toISOString();
//             const isoEndTime = endTime.toISOString();
//             queryInfo.value.createTime = isoStartTime;
//             queryInfo.value.updateTime = isoEndTime;
//         }
//         console.log(timeArray.value);
//         console.log(queryInfo.value.createTime);
//         console.log(queryInfo.value.updateTime);
//     }
// );
onMounted(() => {
  getOpportunitiesListData();
});
</script>

<style scoped>
.business {
  padding: 30px;
  max-height: 100%;
}
</style>
